const registerButton = document.querySelector('.registerbutton');
const rememberCheck = document.getElementById('rememberCheck');

registerButton.addEventListener('click', (e) => {
  e.preventDefault()
  const emailInput = document.getElementById("exampleInputEmail1").value;

  if (emailInput.length === 0) {
    showQuestion("请输入用户名", "warning");
    return;
  }

  const passwordInput = document.getElementById("exampleInputPassword1").value;
  
  if (passwordInput.length < 6) {
    showQuestion("新密码要大于6位数", "warning");
    return;
  }

  const passwordInput2 = document.getElementById("exampleInputPassword2").value;
  
  if (passwordInput2.length < 6) {
    showQuestion("新密码要大于6位数", "warning");
    return;
  }

  if (passwordInput!==passwordInput2) {
    showQuestion("密码不一致", "warning");
    return
  }

  const formData = new FormData();
  const fileInput = document.getElementById('inputGroupFile01');
  const file = fileInput.files[0];

  const newUserObject = {
    username: emailInput,
    password: passwordInput
  };
  formData.append('newUser', new Blob([JSON.stringify(newUserObject)], {
      type: 'application/json'
  }));
  formData.append('imageFile', file);

  console.log("进入注册");

  axios({
    url: 'http://localhost:8080/register',
    method: "post",
    data:formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(result => {
    console.log(result);
    console.log(result.data.data);
    let type = result.data.data.status === "注册成功" ? "success" : "warning";
    console.log(type);
    showQuestion(result.data.data.status, type);

    //注册成功后跳转网页
    if (result.data.data.status === "注册成功") {
      localStorage.setItem('username', emailInput);
      localStorage.setItem('imageFile', result.data.data.image);
      setTimeout(()=> {
        window.location.href='home.html'
        
      },2000)
    }
    

  }).catch(error => {
    console.log(error);
  });
});

function showQuestion(text, statusType) {
  const alertPlaceholder = document.getElementById('alertContainer');

  function alert(message, type) {
    const wrapper = document.createElement('div');
    wrapper.innerHTML = [
      `<div class="alert alert-${type} alert-dismissible" role="alert">`,
      `   <div>${message}</div>`,
      '</div>'
    ].join('');

    alertPlaceholder.append(wrapper);

    setTimeout(() => {
      wrapper.classList.add('show');
    }, 100);

    // 3秒后开始逐渐消失
    setTimeout(() => {
      wrapper.classList.remove('show');
      wrapper.classList.add('fadeOut');
    }, 3000);

    // 5秒后移除元素
    setTimeout(() => {
      wrapper.remove();
    }, 5000);
  }

  alert(text, statusType);
}